#include "vsf.h"

static struct vsfsm_state_t *
vsfav_adapter_evthandler(struct vsfsm_t *sm, vsfsm_evt_t evt)
{
	struct vsfav_adapter_t *adapter = (struct vsfav_adapter_t *)sm->user_data;

	switch (evt)
	{
	case VSFSM_EVT_INIT:
		vsfsm_sem_init(&adapter->in->frame_sync, 0, VSFSM_EVT_USER);
		while (1)
		{
			if (vsfsm_sem_pend(&adapter->in->frame_sync, sm))
				return VSFERR_NONE;
	case VSFSM_EVT_USER:
			if (adapter->on_sync != NULL)
				adapter->on_sync(adapter);
		}
	}
	return NULL;
}

vsf_err_t vsfav_adapter_init(struct vsfav_adapter_t *adapter,
		void (*on_inout)(struct vsfav_adapter_t *adapter, bool isin),
		void (*on_sync)(struct vsfav_adapter_t *adapter))
{
	vsf_err_t err;

	adapter->on_sync = on_sync;
	adapter->adapter.in = adapter->in->stream;
	adapter->adapter.out = adapter->out->stream;
	adapter->adapter.on_inout =
			(void (*)(struct vsf_stream_adapter_t*, bool))on_inout;
	err = vsfstream_adapter_init(&adapter->adapter);
	if (!err)
	{
		adapter->sm.init_state.evt_handler = vsfav_adapter_evthandler;
		adapter->sm.user_data = adapter;
		err = vsfsm_init(&adapter->sm);
	}
	return err;
}
